/**
 * 菜单管理.
 */
var currentNode;
var ref;
$(document).ready(function() {
    //初始化菜单树
    initTreeMenu();
    
    //初始化菜单列表
    initTable();
    $("#spinner").spinner();
 // 获取点击事件
	$('#roleTree').bind("activate_node.jstree", function(obj, e) {
		// 处理代码
		// 获取当前节点
		currentNode = e.node;
		$("#curSelNodeId").val(currentNode.id);
		$("#curSelNodeName").val(currentNode.text);
		//currentNode.children.length;
		// curtable.api().ajax.reload();// 1.10版本之前的
		// $().dataTable() (v1.9 and earlier)
		curtable.ajax.reload();
	});

/*	// 数据删除
	$('#menuTable tbody').on('click', 'A#btnEdit', function() {
		var data = curtable.row($(this).parents('tr')).data();
		// window.location.href="sys/sysmenu/updateInfo.shtml?id="+data.id;
		//alert(data);
		
		 * $.ajax({ url: 'deltable', type: 'POST', dataType:
		 * 'json', data: {id: data[0]}, }) .done(function(data) {
		 * if (data=="success") { tables.ajax.reload(); }; })
		 * .fail(function() { alert("error"); });
		 
	});*/
	// 数据编辑
	$('#menuTable tbody').on('click', 'A#btnDel', function() {
		var data = curtable.row($(this).parents('tr')).data();
		  bootbox.confirm({ 
			  className: 'bootbox-confirm'  ,
		        buttons: {  
		            confirm: {  
		                label: '确认',  
		                className: 'btn btn-sm purple'  
		            },  
		            cancel: {  
		                label: '<i class="fa fa-times"></i>取消',  
		                className: 'btn btn-sm default'  
		            }  
		        },  
		        message: '确认要删除该数据吗?',  
		        callback: function(result) {  
		            if(result) {  
		            	//确定删除
		        		var condition= data.id ; 
		        		var searchURL = basePath + "/sys/sysmenu/ajaxDelete.shtml";
		        		$.ajax({
		        			url : searchURL,
		        			type : "post",
		        			data:JSON.stringify(condition),
		        			contentType : "application/json; charset=UTF-8",
		        			dataType : "json",
		        			success : function(jsonResult) {
		        				if (jsonResult.success) {
		        					//$('#myModal').modal();
		        					//showTip("删除菜单","删除成功!");
		        					bootbox.alert("删除成功!");    
		        				     curtable.ajax.reload();  
		        				} else {
		        					//handleAjaxResponseError(jsonResult);
		        				}
		        			},
		        			// 请求失败
		        			error : function(xhr) {
		        				//loadFinished("dataTable");
		        				//handleAjaxRequestError(xhr);
		        			}

		        		});
		            }
		        }, 
		    }); 
			 
            	
		
	});
	$("#btnSearch").click(function() {
		curtable.ajax.reload();
	});
	//新增打开窗口预先加载数据
	$("#btnAddMenu").click(function(){
		$("#parentName").val($("#curSelNodeName").val());
		$("#parentId").val($("#curSelNodeId").val());
	});
	//关闭时清除数据
	$("#Dialog_addMenu").on("hidden", function() {
	    $(this).removeData("modal");
	});
	//新增保存 
	$("#btnAdd").click(function(){
		var data=getAddCondition();
		var searchURL = basePath + "/sys/sysmenu//ajaxAddInfo.shtml";
		$.ajax({
			url : searchURL,
			type : "post",
			data:data,
			contentType : "application/json; charset=UTF-8",
			dataType : "json",
			success : function(jsonResult) {
				if (jsonResult.success) {
				     $("#Dialog_addMenu").modal('hide');
				} else {
					//handleAjaxResponseError(jsonResult);
				}
			},
			// 请求失败
			error : function(xhr) {
				//loadFinished("dataTable");
				//handleAjaxRequestError(xhr);
			}

		});
	});
});
function initTable() {
    var table = $('#menuTable');
    curtable = table.DataTable($.extend({ // old API: $().dataTable()
        "bSort": false,
        ajax: function(data, callback) {
            $.ajax({
                url: basePath + "/sys/sysmenu/ajaxGetListPage.shtml",
                type: "post",
                data: JSON.stringify(getQueryCondition(data)),
                contentType: "application/json; charset=UTF-8",
                dataType: "json",
                success: function(jsonResult) {
                    if (jsonResult.success) {
                        // 封装返回数据，
                        var returnData = {};
                        returnData.iTotalDisplayRecords = jsonResult.iTotalDisplayRecords;
                        returnData.data = jsonResult.data;
                        returnData.iTotalRecords = jsonResult.iTotalRecords;
                        callback(returnData);

                    } else {
                        var returnData = {};
                        returnData.iTotalDisplayRecords = jsonResult.iTotalDisplayRecords;
                        returnData.data ="";
                        returnData.iTotalRecords = jsonResult.iTotalRecords;
                        callback(returnData);
                    }
                },
                // 请求失败
                error: function(xhr) {
              }
            });
        },
        "columns": [{ // 复选框单元格
            "className": "td-checkbox",
            "data": "id",
            "orderable": false,
            "width": "30px",
            "render": function(data, type, row, meta) {
                return '<input type="checkbox" value=' + data + ' class="iCheck">';
            }
        },
        {
            "data": "name",
            "name": "name",
            "orderable": false
        },
        {
            "data": "parentId",
            "name": "parentId",
            "orderable": false
        },
        {
            "data": "permission",
            "name": "permission",
            "orderable": false
        },
        {
            "data": "isShow",
            "name": "isShow",
            "orderable": false,
            render: function(data, type, row, meta) {
                if (data == '1') {
                    return '是';
                } else {
                    return '否';
                }

            }
        },
        {
            "data": "href",
            "name": "href",
            "orderable": false
        },
        {
            "data": "icon",
            "name": "icon",
            "orderable": false,
            render: function(data, type, row, meta) {
                return '<i  class=' + data + '></i>';
            }
        },
        {
            "data": null,
            "width": "80px",
            "defaultContent": "",
            "orderable": false
        }],
        // 在最后一列增加编辑、删除按钮
        "createdRow": function(row, data, index) {
            // 行渲染回调,在这里可以对该行dom元素进行任何操作
            $('td', row).eq(7).addClass("taC");
            var btnEdit = $('<div class="userM-table-function"><a id="btnEdit" target="_self" href="sys/sysmenu/updateInfo.shtml?id='+data.id+'" class="fa fa-pencil-square text-success"></a> <a id="btnDel" class="fa fa-trash text-danger"></a></div>');
            $('td', row).eq(7).append(btnEdit);
        }
    },
    CONSTANT.DATA_TABLES.DEFAULT_OPTION));
    var tableWrapper = jQuery('#menuTable_wrapper');
	table.find('.group-checkable').change(function() {
		var set = jQuery(this).attr("data-set");
		var checked = jQuery(this).is(":checked");
		jQuery(set).each(function() {
			if (checked) {
				$(this).attr("checked", true);
				$(this).parents('tr').addClass("active");
			} else {
				$(this).attr("checked", false);
				$(this).parents('tr').removeClass("active");
			}
		});
		jQuery.uniform.update(set);
	});

	table.on('change', 'tbody tr .checkboxes', function() {
		$(this).parents('tr').toggleClass("active");
	});

	tableWrapper.find('.dataTables_length select').addClass("form-control input-xsmall input-inline"); // modify

}
// 初始化左侧菜单
function initTreeMenu() {
    var searchURL = basePath + "/ajaxGetUserMenuList.shtml";
    $.ajax({
        url: searchURL,
        type: "post",
        contentType: "application/json; charset=UTF-8",
        dataType: "json",
        success: function(jsonResult) {
            if (jsonResult.success) {
                loadTreeMenu(jsonResult.data);
            } else {
                // handleAjaxResponseError(jsonResult);
            }
        },
        // 请求失败
        error: function(xhr) {
            // loadFinished("dataTable");
            // handleAjaxRequestError(xhr);
        }

    });
}
// 菜单数据加载.
function loadTreeMenu(data) {
	data[0].state="selected : true";
    var menutree = "<ul>";
    for (var i = 0; i < data.length; i++) {
        if (data[i].parentId == '0' && data[i].isShow == '1') {
            menutree += " <li class='jstree-node  jstree-open' id=" + data[i].id + ">" + data[i].name;
            for (var j = 0; j < data.length; j++) {
                menutree += "  <ul>";
                if (data[j].isShow == '1' && data[j].parentId == data[i].id) {

                    menutree += "  <li data-jstree='{ 'icon' : 'fa fa-briefcase icon-state-success ' }' id=" + data[j].id + ">" + data[j].name + "</li>";
                }
                menutree += "  </ul>";
            }
            menutree += " </li >";
        }
    }
    menutree += " </ul>";
    $("#roleTree").html(menutree);
    // 默认展开所有节点
    $('#roleTree').bind("loaded.jstree",
    function(e, data) {
        data.inst.open_all("-1"); // -1 opens all nodes in the Container
    });
    ref=$('#roleTree').jstree({
    	"ui":{ 
    		"initially_select":["1"] 
    		}, 
    		"core" : { 
    		"initially_open" : ["1", "2"] 
    		}, 
    });
}
function getQueryCondition(data) {
	var param = {};
	// 组装排序参数
	/*
	 * if (data.order&&data.order.length&&data.order[0]) { switch
	 * (data.order[0].column) { case 1: param.orderColumn = "name"; break; case
	 * 2: param.orderColumn = "position"; break; case 3: param.orderColumn =
	 * "status"; break; case 4: param.orderColumn = "start_date"; break;
	 * default: param.orderColumn = "name"; break; } param.orderDir =
	 * data.order[0].dir; }
	 */
	// 组装查询参数
	// param.fuzzySearch = userManage.fuzzySearch;
	/*
	 * if (userManage.fuzzySearch) { param.fuzzy = $("#fuzzy-search").val();
	 * }else{ param.name = $("#name-search").val(); param.position =
	 * $("#position-search").val(); param.office = $("#office-search").val();
	 * param.extn = $("#extn-search").val(); param.status =
	 * $("#status-search").val(); param.role = $("#role-search").val(); }
	 */
	// 组装分页参数
	param.STARTINDEX = data.start;
	param.PAGESIZE = data.length;
	param.parentId = $("#curSelNodeId").val();
	param.permission = $("#permission").val();
	param.name = $("#name").val();
	// var node =ref.get_selected();
	//alert(node);
	return param;
}


function getAddCondition() {
	var data=$('#addForm').serializeObject();
	return data;
}
/*$('#menuTable').on('order.dt',
	    function() {
	        alert('排序');
	    }).on('search.dt',
	    function() {
	    	alert('搜索');
	    }).on('page.dt',
	    function() {
	    	alert('翻页');
	    }).dataTable();*/
